import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../models/map_models.dart';
import '../providers/map_editor_provider.dart';

class LayerPanel extends StatelessWidget {
  const LayerPanel({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<MapEditorProvider>(
      builder: (context, provider, child) {
        if (!provider.hasMap) {
          return Container(
            width: 250,
            decoration: BoxDecoration(
              color: Colors.grey[100],
              border: Border.all(color: Colors.grey[300]!),
            ),
            child: const Center(
              child: Text('没有打开的地图'),
            ),
          );
        }

        return Container(
          width: 250,
          decoration: BoxDecoration(
            color: Colors.white,
            border: Border.all(color: Colors.grey[300]!),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              // 标题栏
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey[100],
                  border: Border(
                    bottom: BorderSide(color: Colors.grey[300]!),
                  ),
                ),
                child: Row(
                  children: [
                    const Icon(Icons.layers, size: 20),
                    const SizedBox(width: 8),
                    const Expanded(
                      child: Text(
                        '图层管理',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          fontSize: 14,
                        ),
                      ),
                    ),
                    PopupMenuButton<String>(
                      icon: const Icon(Icons.add, size: 16),
                      tooltip: '添加图层',
                      itemBuilder: (context) => [
                        const PopupMenuItem(
                          value: 'tile_layer',
                          child: Row(
                            children: [
                              Icon(Icons.grid_on, size: 16),
                              SizedBox(width: 8),
                              Text('图块图层'),
                            ],
                          ),
                        ),
                        const PopupMenuItem(
                          value: 'object_layer',
                          child: Row(
                            children: [
                              Icon(Icons.category, size: 16),
                              SizedBox(width: 8),
                              Text('对象图层'),
                            ],
                          ),
                        ),
                      ],
                      onSelected: (value) {
                        if (value == 'tile_layer') {
                          _showAddLayerDialog(context, false);
                        } else if (value == 'object_layer') {
                          _showAddLayerDialog(context, true);
                        }
                      },
                    ),
                  ],
                ),
              ),
              
              // 图层列表
              Expanded(
                child: ListView.builder(
                  padding: const EdgeInsets.all(8),
                  itemCount: provider.currentMap!.layers.length,
                  itemBuilder: (context, index) {
                    final layer = provider.currentMap!.layers[index];
                    final isSelected = index == provider.currentLayerIndex;
                    
                    return _buildLayerItem(
                      context, 
                      provider, 
                      layer, 
                      index, 
                      isSelected
                    );
                  },
                ),
              ),
              
              // 底部操作栏
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.grey[50],
                  border: Border(
                    top: BorderSide(color: Colors.grey[300]!),
                  ),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                  children: [
                    _buildActionButton(
                      icon: Icons.arrow_upward,
                      tooltip: '前置图层',
                      onPressed: provider.currentLayerIndex > 0
                        ? () => _moveLayerUp(provider)
                        : null,
                    ),
                    _buildActionButton(
                      icon: Icons.arrow_downward,
                      tooltip: '后置图层',
                      onPressed: provider.currentLayerIndex < provider.currentMap!.layers.length - 1
                        ? () => _moveLayerDown(provider)
                        : null,
                    ),
                    _buildActionButton(
                      icon: Icons.content_copy,
                      tooltip: '复制图层',
                      onPressed: () => _duplicateLayer(provider),
                    ),
                    _buildActionButton(
                      icon: Icons.delete,
                      tooltip: '删除图层',
                      onPressed: provider.currentMap!.layers.length > 1
                        ? () => _showDeleteLayerDialog(context, provider)
                        : null,
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildLayerItem(
    BuildContext context,
    MapEditorProvider provider,
    MapLayer layer,
    int index,
    bool isSelected,
  ) {
    return Container(
      margin: const EdgeInsets.only(bottom: 4),
      decoration: BoxDecoration(
        color: isSelected ? Colors.blue[50] : Colors.transparent,
        border: Border.all(
          color: isSelected ? Colors.blue : Colors.grey[300]!,
          width: isSelected ? 2 : 1,
        ),
        borderRadius: BorderRadius.circular(4),
      ),
      child: ListTile(
        dense: true,
        contentPadding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
        leading: Container(
          width: 24,
          height: 24,
          decoration: BoxDecoration(
            color: layer.isObjectLayer ? Colors.orange[100] : Colors.blue[100],
            border: Border.all(color: Colors.grey[400]!),
            borderRadius: BorderRadius.circular(2),
          ),
          child: Icon(
            layer.isObjectLayer ? Icons.category : Icons.grid_on,
            size: 16,
            color: layer.isObjectLayer ? Colors.orange[700] : Colors.blue[700],
          ),
        ),
        title: Text(
          layer.name,
          style: const TextStyle(fontSize: 12),
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
        ),
        subtitle: Text(
          '透明度: ${(layer.opacity * 100).toInt()}%',
          style: const TextStyle(fontSize: 10),
        ),
        trailing: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            IconButton(
              icon: Icon(
                layer.visible ? Icons.visibility : Icons.visibility_off,
                size: 16,
                color: layer.visible ? Colors.blue : Colors.grey,
              ),
              onPressed: () => _toggleLayerVisibility(provider, index),
              tooltip: layer.visible ? '隐藏图层' : '显示图层',
              constraints: const BoxConstraints(
                minWidth: 24,
                minHeight: 24,
              ),
            ),
            PopupMenuButton<String>(
              icon: const Icon(Icons.more_vert, size: 16),
              itemBuilder: (context) => [
                const PopupMenuItem(
                  value: 'rename',
                  child: Row(
                    children: [
                      Icon(Icons.edit, size: 16),
                      SizedBox(width: 8),
                      Text('重命名'),
                    ],
                  ),
                ),
                const PopupMenuItem(
                  value: 'opacity',
                  child: Row(
                    children: [
                      Icon(Icons.opacity, size: 16),
                      SizedBox(width: 8),
                      Text('调整透明度'),
                    ],
                  ),
                ),
                const PopupMenuItem(
                  value: 'clear',
                  child: Row(
                    children: [
                      Icon(Icons.clear_all, size: 16),
                      SizedBox(width: 8),
                      Text('清空图层'),
                    ],
                  ),
                ),
              ],
              onSelected: (value) {
                switch (value) {
                  case 'rename':
                    _showRenameLayerDialog(context, provider, index);
                    break;
                  case 'opacity':
                    _showOpacityDialog(context, provider, index);
                    break;
                  case 'clear':
                    _showClearLayerDialog(context, provider, index);
                    break;
                }
              },
            ),
          ],
        ),
        onTap: () => provider.selectLayer(index),
      ),
    );
  }

  Widget _buildActionButton({
    required IconData icon,
    required String tooltip,
    VoidCallback? onPressed,
  }) {
    return Tooltip(
      message: tooltip,
      child: IconButton(
        icon: Icon(icon, size: 16),
        onPressed: onPressed,
        constraints: const BoxConstraints(
          minWidth: 32,
          minHeight: 32,
        ),
      ),
    );
  }

  void _showAddLayerDialog(BuildContext context, bool isObjectLayer) {
    final nameController = TextEditingController(
      text: isObjectLayer ? '新对象层' : '新图层',
    );

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text(isObjectLayer ? '添加对象层' : '添加图块层'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: '图层名称',
                border: OutlineInputBorder(),
              ),
              autofocus: true,
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              final provider = Provider.of<MapEditorProvider>(context, listen: false);
              provider.addLayer(nameController.text, isObjectLayer: isObjectLayer);
              Navigator.of(context).pop();
            },
            child: const Text('添加'),
          ),
        ],
      ),
    );
  }

  void _showRenameLayerDialog(BuildContext context, MapEditorProvider provider, int layerIndex) {
    final layer = provider.currentMap!.layers[layerIndex];
    final nameController = TextEditingController(text: layer.name);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('重命名图层'),
        content: TextField(
          controller: nameController,
          decoration: const InputDecoration(
            labelText: '新名称',
            border: OutlineInputBorder(),
          ),
          autofocus: true,
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.renameLayer(layerIndex, nameController.text);
              Navigator.of(context).pop();
            },
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  void _showOpacityDialog(BuildContext context, MapEditorProvider provider, int layerIndex) {
    final layer = provider.currentMap!.layers[layerIndex];
    double opacity = layer.opacity;

    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => AlertDialog(
          title: const Text('调整透明度'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              Text('透明度: ${(opacity * 100).toInt()}%'),
              const SizedBox(height: 16),
              Slider(
                value: opacity,
                min: 0.0,
                max: 1.0,
                divisions: 100,
                onChanged: (value) {
                  setState(() {
                    opacity = value;
                  });
                },
              ),
            ],
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () {
                // TODO: 实现设置图层透明度的方法
                Navigator.of(context).pop();
              },
              child: const Text('确定'),
            ),
          ],
        ),
      ),
    );
  }

  void _showDeleteLayerDialog(BuildContext context, MapEditorProvider provider) {
    final currentLayer = provider.currentMap!.layers[provider.currentLayerIndex];
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('删除图层'),
        content: Text('确定要删除图层 "${currentLayer.name}" 吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              provider.deleteCurrentLayer();
              Navigator.of(context).pop();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  void _showClearLayerDialog(BuildContext context, MapEditorProvider provider, int layerIndex) {
    final layer = provider.currentMap!.layers[layerIndex];
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('清空图层'),
        content: Text('确定要清空图层 "${layer.name}" 的所有内容吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              // TODO: 实现清空图层的方法
              Navigator.of(context).pop();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
              foregroundColor: Colors.white,
            ),
            child: const Text('清空'),
          ),
        ],
      ),
    );
  }

  void _toggleLayerVisibility(MapEditorProvider provider, int layerIndex) {
    final currentIndex = provider.currentLayerIndex;
    provider.selectLayer(layerIndex);
    provider.toggleLayerVisibility();
    // 切换回原来的图层
    if (currentIndex < provider.currentMap!.layers.length) {
      provider.selectLayer(currentIndex);
    }
  }

  void _moveLayerUp(MapEditorProvider provider) {
    // TODO: 实现前置图层功能
  }

  void _moveLayerDown(MapEditorProvider provider) {
    // TODO: 实现后置图层功能
  }

  void _duplicateLayer(MapEditorProvider provider) {
    final currentLayer = provider.currentMap!.layers[provider.currentLayerIndex];
    final newName = '${currentLayer.name}_副本';
    
    // 创建图层副本
    final duplicatedLayer = MapLayer(
      id: (provider.currentMap!.nextLayerId + 1).toString(),
      name: newName,
      width: currentLayer.width,
      height: currentLayer.height,
      data: List.from(currentLayer.data.map((row) => List.from(row))),
      visible: currentLayer.visible,
      opacity: currentLayer.opacity,
      isObjectLayer: currentLayer.isObjectLayer,
    );
    
    provider.addLayer(newName, isObjectLayer: currentLayer.isObjectLayer);
  }
}